package browser;

/* 
 * Author: rendy.jr
 * Date: Jun 10, 2011
 * 6.005 Elements of Software Construction
 * Rendy Bambang Junior
 * rendy.jr@gmail.com
 * 
 * This class represent a browser. It has a cache.
 * Responsible for :
 * - fetching pages
 * 
 */

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;

import string.Match;
import widget.Weather;

public class Browser {
	// browser cache
	public static Cache cache = new VectorCache();
	
	/* fetch method try to retrieve url content
	 * @throws MalformedURLException 
	 */
	public static String fetch(String urlString) throws MalformedURLException, IOException{
		URL url = new URL(urlString);
		
		//open a stream for web server
		InputStream input = url.openStream();
		InputStreamReader reader = new InputStreamReader(input);
		
		// create a stream that appends data together into a String
		StringWriter writer = new StringWriter();
		
		//copy from the web server stream to string stream
		copyStream(reader,writer);
		
		return writer.toString();
	}
	/*
	 * copyStream copies received stream to writer 
	 */
	public static void copyStream(InputStreamReader from, StringWriter to) throws IOException{
		try{
			char[] buffer = new char[10000];
			
			while(true){
				int n = from.read(buffer);
				if(n == -1) break;
				to.write(buffer,0,n);			
			}
		}
		finally{
			from.close();
			to.close();
		}
	}
	
	public static void main(String args[]){
		try {
//			Weather w;
//			w = new Weather("02139");
//			System.out.println("Condition : "+w.getCondition());
//			System.out.println("Temperature : "+ w.getTemperature());
			fetch("http://www.mit.edu/foobar"); 
		} catch (MalformedURLException e) {
		System.out.println("Bad URL: " + e);
		} catch (IOException e) { 
		System.out.println("IO problem: " + e); 
		} 
	}
}
